<?php
/**
 * Index page controller
 *
 * @author Dima
 *
 */

class IndexController extends modules_default_controllers_ControllerBase
{
	protected $_bForLoggedUsersOnly = true;

//----------------------------------------------------------------------------------------------------
	
    public $ajaxable = array(
//        'update'        => array('json'),
    );
    
//----------------------------------------------------------------------------------------------------

	public function init()
	{
//		if (! $this->getRequest()->isXmlHttpRequest())
//        {
            parent::init();
//        }	
		$this->view->title = 'Home';
	}

	//----------------------------------------------------------------------------------------------------

	public function pdfAction()
	{

$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender();


		$oRequest = $this->getRequest();
		$archive  = $oRequest->getParam('archive');
        $month    =  $oRequest->getParam('month');  
        $year     =  $oRequest->getParam('year'); 
        
		if (!$archive)
		{
  	        $startDate  = date('Y-m-1');
		    $endDate    = date('Y-m-t');
		}  
		else
		{
			$startDate    = $archive . '-1';
			$endDate      = date('Y-m-t', strtotime($startDate));
		}
		
			list($year, $month, $day) = explode('-', $startDate);
        
		$aIdentity    = Zend_Auth::getInstance()->getIdentity();
        $idUser       = $aIdentity['User_id'];
        $reportPeriod = models_PeriodMapper::findByIdUser($idUser, $startDate);
        $user         = models_UserMapper::findById($idUser);
		$allProject   = models_ProjectMapper::findByIdUser($idUser, $startDate, $endDate);
		$allReport    = models_ReportMapper::findByIdUser($idUser, $startDate, $endDate);
		$retReport    = array();
		foreach ($allReport as $report)
		{
			$day = date('j', strtotime($report['date']));
			$retReport[$day][$report['id_project']] = $report['hour'];
		}

		$archiveDate    = models_ReportMapper::getAllArchiveDate();
        $attach         = models_PrinttimesheetMapper::findByIdUserAndDate($idUser, $startDate);
        $endDay         = date('t', strtotime($endDate));
        
        
    //    print_r($allProject);
    //    print_r($retReport);
        
        $pdf= new VLFN_Fpdf('L');
        $pdf->AddPage();
        $pdf->SetFont('Arial','', 16);
        $pdf->Image('i/logo.png', 10, 5, 90, 20);
        $pdf->SetFontSize(7);
        $pdf->Cell(150, 20, "");
        $pdf->Ln(10);
        $pdf->Ln();
        
        $headerW = 100;
        $headerH = 4;
        
        $pdf->Cell($headerW, $headerH, "");
        $pdf->Cell($headerW, $headerH, "TIME SHEET");
        $pdf->Cell($headerW, $headerH, "");
        $pdf->Ln();
        $pdf->Ln();
        

        $w = array(20, 60, 20, 60, 20, 80); 
	            
	            $pdf->Cell($w[0], 6, 'Name:', 'BT');
	            $pdf->Cell($w[1], 6, $user->name,   'BT');
	            $pdf->Cell($w[2], 6, 'Afkorting:',  'BT');
                $pdf->Cell($w[3], 6, $user->afk, 'BT');
                $pdf->Cell($w[4], 6, 'Periode:',   'BT');
                $pdf->Cell($w[5], 6, date('F Y', strtotime($endDate)),  'BT');
                        
	            $pdf->Ln();
	            $pdf->Ln();
	            $pdf->Ln();
	            
        $w = array(15, 25);
        for($i = 1; $i <= $endDay; $i++)
        {
        	$w[] = 7;
        }
        
        $pdf->Cell($w[0], 6, '', 'LBT');
	    $pdf->Cell($w[1], 6, '',   'BT');
	    for($i = 1; $i <= $endDay; $i++)
        {
        	 $pdf->Cell($w[$i+1], 6, date('D', strtotime($year . '-' .  $month . '-' . $i)),  'BT');
        }
	    $pdf->Cell($w[0], 6, '', 'RBT');
	    $pdf->Ln();
	    
	    $pdf->Cell($w[0], 6, '', 'LBT');
	    $pdf->Cell($w[1], 6, '',   'BT');
	    for($i = 1; $i <= $endDay; $i++)
        {
        	 $pdf->Cell($w[$i+1], 6, $i,  'BT');
        }
	    $pdf->Cell($w[0], 6, 'Totaal', 'RBT');
	    $pdf->Ln();
	    
        foreach($allProject as $project)
        {
        	$tr = 0;
        	$pdf->Cell($w[0], 6, $project['project_num'], 'LBT');
	    	$pdf->Cell($w[1], 6, $project['name'],   'BT');
	    	/*
	    	if ((1 != $project['base']))
		     {	
		        	$aStartDate       = explode('-', $project['start_date']);
		        	(int) $startDay   = $aStartDate[2];
		        	
		        	$aEndDate         = explode('-', $project['end_date']);
	                (int) $tEndDay     = $aEndDate[2];
	                (int) $endYear    = $aEndDate[0];
	                
//	                print_r($aEndDate);
	                
	                if($aStartDate[1] == $aEndDate[1])
	                {
	                	$endDay   = $tEndDay;
	                }
	                
	                if('0000-00-00' == $project['start_date'])
	                {
	                	$startDay = 1;
	                }
	                
		            if('0000-00-00' != $project['end_date'])
                    {
                        $endDay   = $tEndDay;
                    }
                    
                    if($endYear <=  $year)
                    {
                        $endDay   = $tEndDay;
                    }
		        }
		        else
		        {
		        	$startDay = 1;
		        } */
            for($i = 1; $i <= $endDay; $i++)
        	{
        		$val = '';
	           	   if (isset($retReport[$i]))
	           	       if (isset($retReport[$i][$project['id']]))
	           	           $val = $retReport[$i][$project['id']] ;
        		
        	 	$pdf->Cell($w[$i+1], 6, $val,  'BT');
        	 	
        	 	$tr += $val;
        	 	if(1 == $project['billable']) {
        	 	if (isset($total[$i]))
                        $total[$i] += $val;
                   else
                        $total[$i] = $val;
        	 	} else {
        	 	if (isset($total_nb[$i]))
                        $total_nb[$i] += $val;
                   else
                        $total_nb[$i] = $val;
        	 		
        	 	}
        	}
        	$pdf->Cell($w[0], 6, $tr, 'RBT');
        	
        	$pdf->Ln();
        }

        $pdf->Cell($w[0], 6, '', 'LBT');
	    $pdf->Cell($w[1], 6, 'Billable hours:',   'BT');
	    $all_total = 0;
        for($i = 1; $i <= $endDay; $i++)
      	{
          	$ct =  $total[$i] <= 8 ? $total[$i] != 0 ? $total[$i] : '' : 8;
            $pdf->Cell($w[$i+1], 6, number_format($ct, 1, '.', ''),  'BT');
            $all_total += $ct;
      	}
       	$pdf->Cell($w[0], 6, $all_total, 'RBT');
       	$pdf->Ln();	           
       	
        $pdf->Cell($w[0], 6, '', 'LBT');
	    $pdf->Cell($w[1], 6, 'Billable overtime:',   'BT');
	    $all_overtime = 0;
        for($i = 1; $i <= $endDay; $i++)
      	{
      		$cot =   $total[$i] > 8 ? $total[$i] - 8 : '';
            $all_overtime += $cot;
            $pdf->Cell($w[$i+1], 6, number_format($cot, 1, '.', ''),  'BT');
      	}
       	$pdf->Cell($w[0], 6, $all_overtime, 'RBT');
       	$pdf->Ln();	   
       	
        $pdf->Cell($w[0], 6, '', 'LBT');
	    $pdf->Cell($w[1], 6, 'Total billable:',   'BT');
	    $all_bill = 0;
        for($i = 1; $i <= $endDay; $i++)
      	{
      		$cot =   $total[$i];
            $all_bill += $cot;
            $pdf->Cell($w[$i+1], 6, number_format($cot, 1, '.', ''),  'BT');
      	}
       	$pdf->Cell($w[0], 6, $all_bill, 'RBT');
       	$pdf->Ln();	      

       	$pdf->Cell($w[0], 6, '', 'LBT');
	    $pdf->Cell($w[1], 6, 'Non-billable hours:',   'BT');
	    $all_notbill = 0;
        for($i = 1; $i <= $endDay; $i++)
      	{
      		$cot =   $total_nb[$i];
            $all_notbill += $cot;
            $pdf->Cell($w[$i+1], 6, number_format($cot, 1, '.', ''),  'BT');
      	}
       	$pdf->Cell($w[0], 6, $all_notbill, 'RBT');
       	$pdf->Ln();	 
       	$pdf->Ln(5);	
       	
       	$pdf->Cell(60, 18, 'Handtekening medewerker:',  'LRBT'); 
       	$pdf->Cell(25, 18, '',  ''); 
       	$pdf->Cell(60, 18, 'Handtekening opdrachtgever:',  'LRBT'); 
       	$pdf->Cell(35, 18, '',  ''); 
       	$pdf->Cell(60, 18, 'Opmerkingen:',  'LRBT'); 
        	
       	
	            
        $pdf->Output();
        
        
        /*
            
        if(isset($attach[0])) 
        {   
            $this->view->attach   = $attach[0];	
        }	
		$this->view->archiveDate  = $archiveDate;
		$this->view->archive      = $archive;
		$this->view->endDay       = date('t', strtotime($endDate));
		$this->view->user         = $user;
        $this->view->period       = date('F Y', strtotime($endDate));
        $this->view->allProject   = $allProject;
        $this->view->allReport    = $retReport;        
        $this->view->month 		  = $month;
        $this->view->year 		  = $year;
        if (isset($reportPeriod[0]))
        {
            $this->view->reportPeriod       = $reportPeriod[0];
        }
        */
	}
		
	//----------------------------------------------------------------------------------------------------

	public function indexAction()
	{
		$this->view->headScript()->appendFile('/js/report.js');    
		$oRequest         = $this->getRequest();

	    if ('print' == $oRequest->getParam('view'))
        {
//            $this->_helper->layout->disableLayout();
            $this->view->layout()->setLayoutPath(APPLICATION_PATH . '/modules/default/layouts/print');
            $this->view->views   = 'print';
        }
		
		$archive          = $oRequest->getParam('archive');    
        if ('Current month' == $archive)
        {
            $archive = false; 
        }
            
		if (!$archive)
		{
  	        $startDate  = date('Y-m-1');
		    $endDate    = date('Y-m-t');
		}  
		else
		{
			$startDate    = $archive . '-1';
			$endDate      = date('Y-m-t', strtotime($startDate));
		}
		
		
		list($year, $month, $day) = explode('-', $startDate);
        
		$aIdentity    = Zend_Auth::getInstance()->getIdentity();
        $idUser       = $aIdentity['User_id'];
        $reportPeriod = models_PeriodMapper::findByIdUser($idUser, $startDate);
        $user         = models_UserMapper::findById($idUser);
		$allProject   = models_ProjectMapper::findByIdUser($idUser, $startDate, $endDate);
		$allReport    = models_ReportMapper::findByIdUser($idUser, $startDate, $endDate);
		$retReport    = array();
		foreach ($allReport as $report)
		{
			$day = date('j', strtotime($report['date']));
			$retReport[$day][$report['id_project']] = $report['hour'];
		}

		$archiveDate    = models_ReportMapper::getAllArchiveDate();
        $attach         = models_PrinttimesheetMapper::findByIdUserAndDate($idUser, $startDate);
        
            
        if(isset($attach[0])) 
        {   
            $this->view->attach   = $attach[0];	
        }	
		$this->view->archiveDate  = $archiveDate;
		$this->view->archive      = $archive;
		$this->view->endDay       = date('t', strtotime($endDate));
		$this->view->user         = $user;
        $this->view->period       = date('F Y', strtotime($endDate));
        $this->view->allProject   = $allProject;
        $this->view->allReport    = $retReport;        
        $this->view->month 		  = $month;
        $this->view->year 		  = $year;
        if (isset($reportPeriod[0]))
        {
            $this->view->reportPeriod       = $reportPeriod[0];
        }
        
	}

//----------------------------------------------------------------------------------------------------

    public function addAction()
    {
    	$oRequest = $this->getRequest();
    	
        $startDate         = date('Y-m-1 00:00:00');
        $endDate           = date('Y-m-t 00:00:00');
    }
	
//----------------------------------------------------------------------------------------------------

    public function addprojectAction()
    {
        $oRequest          = $this->getRequest();
        
        
        if ($oRequest->isPost() && '' != $oRequest->getParam('name'))
        {
            $name                   = strip_tags($oRequest->getParam('name'));
            $base                   = strip_tags($oRequest->getParam('base'));
            $project_num 			= strip_tags($oRequest->getParam('project_num'));
            $start_date				= date('Y-m-1 00:00:00');
            $end_date				= date('Y-12-t 00:00:00');

            $aData['name']          = $name;
            $aData['project_num']   = $project_num;
            $aData['start_date']    = $start_date;
            $aData['end_date']      = $end_date;
            $aData['base']          = 0 ;
            $aData['time_off']      = 0 ;
            
            $exist_project          = models_ProjectMapper::findByName($name);
            if (isset($exist_project->id))
            {
            	$id = $exist_project->id;
            	$aData = array('in_list' => 1);
                models_ProjectMapper::edit($id, $aData);
            }
            else
            {
                $idItem                 = models_ProjectMapper::save($aData);
                
                $aIdentity    = Zend_Auth::getInstance()->getIdentity();
        		$idUser       = $aIdentity['User_id'];
        		$aData		  = array();
        		
               	$aData['id_user']       = $idUser;
                $aData['id_project']    = $idItem;
                $aData['start_date']    = $start_date;
                $aData['end_date']      = $end_date;
                $aData['endless']       = 0 ;
             //   print_r($aData); die;        
                $idItem = models_UsertoprojectMapper::save($aData);
            }
            $this->_redirect('/');
        }
        else
        {
        	$val = array('project_num' => date('YmdHi'));
        	$this->view->val = $val;
        }
    }
    
//----------------------------------------------------------------------------------------------------

    public function updateAction()
    {
    	$this->_helper->viewRenderer->setNoRender();
		$this->_helper->layout->disableLayout();
		
        $oRequest = $this->getRequest();
        
        $id       =  $oRequest->getParam('id');
        $hour     =  $oRequest->getParam('send_hour');        
        $month    =  $oRequest->getParam('month');  
        $year     =  $oRequest->getParam('year');          
        
        $this->view->ret    = $id;
        
//      $allProject   = models_ProjectMapper::findByIdUser($idUser, $startDate, $endDate);
//      $this->view->featuredCards = $featured;
        list($day, $idProject) = explode('_', $id);

        $aIdentity  = Zend_Auth::getInstance()->getIdentity();
        $idUser     = $aIdentity['User_id'];
        
        $aData['id_user'] 		= $idUser;
        $aData['id_project'] 	= $idProject;
        $aData['hour'] 			= $hour; 
        $aData['date'] 			= $year . '-' . $month . '-' . $day; 
        
//        print_r($aData);
      	if ($id = models_ReportMapper::findRecord($idUser, $idProject, $year . '-' . $month . '-' . $day))
      	{
      		models_ReportMapper::update($id->id, $aData);
      	}
      	else
      	{
        	models_ReportMapper::save($aData);
      	}
    }

//----------------------------------------------------------------------------------------------------
 
    public function periodAction()
    {

        $oRequest  = $this->getRequest();
        $idUser    = $oRequest->getParam('id_user');
        $action    = $oRequest->getParam('do_action');
        $year      = $oRequest->getParam('year');
        $month     = $oRequest->getParam('month');
        
        $id        =  models_PeriodMapper::findByIdUser($idUser, $year . '-' . $month . '-1');
        $aData     = array('status' => $action );

        if (isset($id[0]['id']))
        {
            models_PeriodMapper::edit($id[0]['id'], $aData);
        }
        else
        {
            $aData     = array('status'   => $action,
                               'id_user'  => $idUser,
                               'date'     =>  $year . '-' . $month . '-1',
                              );
            models_PeriodMapper::save($aData);
        }
        
        $this->_redirect('/?id_user=' . $idUser . '&archive=' . $year . '-' . $month);
    }
    
//----------------------------------------------------------------------------------------------------
     
    public function attachAction()
    {

        $oRequest  = $this->getRequest();
        $idUser    = $oRequest->getParam('id_user');
        $action    = $oRequest->getParam('do_action');
        $year      = $oRequest->getParam('year');
        $month     = $oRequest->getParam('month');
        
        $id        =  models_PeriodMapper::findByIdUser($idUser, $year . '-' . $month . '-1');
//        $aData     = array('status' => $action );

        if ($oRequest->isPost())
        {
            $file_name       = strip_tags($oRequest->getParam('file_name'));

            if ('' != $_FILES['file_name']['name'])
            {
                $userFile    = $_FILES['file_name'];
                $tmpFile     = $userFile['tmp_name'];
                $nameFile    = $userFile['name'];
                list($name, $ext) = explode('.', $nameFile);
                
                $newFileName =  $year . '-' . $month . '-'. $idUser . '.' . $ext;

                $JobDir = $_SERVER['DOCUMENT_ROOT'] . '/attach';
                if( ! file_exists($JobDir))
                {
                    mkdir($JobDir) or die;
                    chmod($JobDir, octdec('0777'));
                }

                $JobDir = $_SERVER['DOCUMENT_ROOT'] . '/attach/' . $newFileName;

                if(rename($tmpFile, $JobDir ))
                {
                    chmod($JobDir, octdec('0777'));
                }

                $aData['id_user']      = $idUser;
                $aData['date']         = $year . '-' . $month . '-1';
                $aData['file_name']    = $newFileName;
                $id                    = models_PrinttimesheetMapper::findByIdUserAndDate($idUser, $year . '-' . $month . '-1');
                
                if (isset($id[0]['id']))
                {
                     $idItem = models_PrinttimesheetMapper::update($id[0]['id'], $aData);
                }
                else
                {
                    $idItem = models_PrinttimesheetMapper::saveArray($aData, 'models_DbTable_Printtimesheet');
                }
            }
        }

        $this->_redirect('/?archive=' . $year . '-' . $month);
    }
}